package com.ithuameng.admin.app.system.controller;

import com.ithuameng.admin.constants.CommonConstants;
import com.ithuameng.admin.security.JwtTokenProvider;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static java.util.Optional.ofNullable;
import static org.apache.commons.lang3.StringUtils.removeStart;

/**
 * 控制器公共方法
 *
 * @author ithuameng
 */
@Component
public class AdminBaseController {

	@Resource
	private JwtTokenProvider jwtTokenProvider;

	/**
	 * 获取当前登录用户编号
	 * 
	 * @param request HttpServletRequest
	 * @return 当前登录用户编号
	 */
	protected Long getLoginUserId(HttpServletRequest request) {
		Optional<String> userId = Optional.of(getMetaData(request)).map(map -> map.get(CommonConstants.USER_ID));
		return userId.map(Long::parseLong).orElse(null);
	}

	/**
	 * 获取令牌中登录信息
	 * 
	 * @param request HttpServletRequest
	 * @return 令牌中登录信息
	 */
	protected Map<String, String> getMetaData(HttpServletRequest request) {
		final String param = ofNullable(request.getHeader(AUTHORIZATION)).orElse(request.getParameter("t"));
		final String token = ofNullable(param).map(value -> removeStart(value, CommonConstants.BEARER))
				.map(String::trim).orElse("");
		return jwtTokenProvider.verify(token);
	}
}
